﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WarehouseManager.Common;
using SigowayCommonLib.ADO;
using SigowayCommonLib;

namespace WarehouseManager.View
{
    public partial class SearchPatientForm : Form
    {
        /// <summary>
        ///  操作员
        /// </summary>
        private string strOperator = string.Empty;
        
        private DBManager dbManager;
        private DataTable datSource = null;
        public SearchPatientForm(string _operator)
        {
            InitializeComponent();
            this.strOperator = _operator;
            this.label4.Text = this.strOperator;
            this.label5.Text = DateTimeUtil.GetCurrentDate();
            datSource = CreateDataTable();
            dbManager = DBManager.GetDBManager();
            datGridList.DataSource = datSource;
        }
        private void MergeData(DataTable datTemp)
        {
            DataRow darSource = null;
            foreach (DataRow dar in datTemp.Rows)
            {
                darSource = datSource.NewRow();
                //编号
                darSource[ConstInfo.COL_NUMBER] = dar[ConstInfo.COL_NUMBER];
                //姓名
                darSource[ConstInfo.COL_PATIENT_NAME] = dar[ConstInfo.COL_PATIENT_NAME];
                //拼音码
                darSource[ConstInfo.COL_PYCODE] = dar[ConstInfo.COL_PYCODE];
                //联系电话
                darSource[ConstInfo.COL_MOBILENO] = dar[ConstInfo.COL_MOBILENO];
                //家庭住址
                darSource[ConstInfo.COL_ADDR] = dar[ConstInfo.COL_ADDR];
                //出生日期
                darSource[ConstInfo.COL_BIRTHDAY] = dar[ConstInfo.COL_BIRTHDAY];
                //身份证号
                darSource[ConstInfo.COL_PIDNUMBER] = dar[ConstInfo.COL_PIDNUMBER];
                //性别
                darSource[ConstInfo.COL_SEX] = dar[ConstInfo.COL_SEX].ToString()=="1"?"女":"男";
                //入院日期
                darSource[ConstInfo.COL_RYDATE] = dar[ConstInfo.COL_RYDATE];
                //出院日期
                darSource[ConstInfo.COL_CYDATE] = dar[ConstInfo.COL_CYDATE];
                //疾病名称
                darSource[ConstInfo.COL_SICKNESSNAME] = dar[ConstInfo.COL_SICKNESSNAME];
                //工作单位
                darSource[ConstInfo.COL_WORKPLACE] = dar[ConstInfo.COL_WORKPLACE];
                //备注
                darSource[ConstInfo.COL_NOTE] = dar[ConstInfo.COL_NOTE];
                datSource.Rows.Add(darSource);
            }
            darSource.AcceptChanges();
        }
        private DataTable CreateDataTable()
        {
            DataTable datTemp = new DataTable();
            //编号
            datTemp.Columns.Add(ConstInfo.COL_NUMBER, typeof(string));
            //姓名
            datTemp.Columns.Add(ConstInfo.COL_PATIENT_NAME, typeof(string));
            //拼音码
            datTemp.Columns.Add(ConstInfo.COL_PYCODE, typeof(string));
            //联系电话
            datTemp.Columns.Add(ConstInfo.COL_MOBILENO, typeof(string));
            //家庭住址
            datTemp.Columns.Add(ConstInfo.COL_ADDR, typeof(string));
            //出生日期
            datTemp.Columns.Add(ConstInfo.COL_BIRTHDAY, typeof(string));
            //身份证号
            datTemp.Columns.Add(ConstInfo.COL_PIDNUMBER, typeof(string));
            //性别
            datTemp.Columns.Add(ConstInfo.COL_SEX, typeof(string));
            //入院日期
            datTemp.Columns.Add(ConstInfo.COL_RYDATE, typeof(string));
            //出院日期
            datTemp.Columns.Add(ConstInfo.COL_CYDATE, typeof(string));
            //疾病名称
            datTemp.Columns.Add(ConstInfo.COL_SICKNESSNAME, typeof(string));
            //工作单位
            datTemp.Columns.Add(ConstInfo.COL_WORKPLACE, typeof(string));
            //备注
            datTemp.Columns.Add(ConstInfo.COL_NOTE, typeof(string));
            return datTemp;
        }
        private void btnSerach_Click(object sender, EventArgs e)
        {
            getPatientInfo(true);

        }

        private void getPatientInfo(bool showMsg)
        {
            datSource.Clear();
            IDictionary<string, object> dicParameter = null;
            string sqlText = string.Empty;
            if (!string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                sqlText = string.Format("SELECT * FROM PatientInfo WHERE {0} like ?", ConstInfo.COL_PATIENT_NAME);
                dicParameter = new Dictionary<string, object>();
                dicParameter.Add(ConstInfo.COL_PATIENT_NAME, "%" + this.txtName.Text.Trim() + "%");
            }
            else
            {
                sqlText = "SELECT * FROM PatientInfo";
            }
            try
            {
                DataTable datTemp = this.dbManager.ExecuteQuery(new SQLObject(sqlText, dicParameter));
                if (null != datTemp && datTemp.Rows.Count > 0)
                {
                    MergeData(datTemp);
                    return;
                }

                if (showMsg)
                {
                    MessageBoxHelp.ShowMsgWarning("患者信息不存在！"); 
                }
                txtName.Focus();
            }
            catch (Exception ex)
            {
                if (showMsg)
                {
                    MessageBoxHelp.ShowMsgError("患者信息取得失败,具体错误信息如下：\r\n" + ex.Message); 
                }
                LogManager.WriteLine("患者信息取得失败,具体错误信息如下:\r\nException={0}", ex);
            }
        }

        private void txtName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)37)
            {
                e.Handled = true;
            }
        }


        /// <summary>
        /// 删除处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            IEnumerable<String> delFlags = getSelectedPatientNo();
            if (delFlags == null || delFlags.Count() == 0)
            {
                return;
            }

            if(MessageBoxHelp.ShowMsgQuestionYesNo("将删除以下选中的患者信息，是否继续？") != DialogResult.Yes)
            {
                return;
            }

            string strNumbers = string.Join(",", delFlags.ToArray());

            string sqlText = string.Format("DELETE FROM PatientInfo WHERE {0} IN ({1})", ConstInfo.COL_NUMBER, strNumbers);
            try
            {
                int nResult = this.dbManager.ExecuteNonQuery(new SQLObject(sqlText, null));
                if (nResult > 0)
                {
                    MessageBoxHelp.ShowMsgWarning("患者信息删除成功！");
                    this.btnDelete.Enabled = false;
                    getPatientInfo(false);
                }
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("患者信息删除失败,具体错误信息如下：\r\n" + ex.Message);
                LogManager.WriteLine("患者信息删除失败,具体错误信息如下：\r\nException={0}", ex);
            }
        }

        private void datGridList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex != 0)
            {
                return;
            }

            IEnumerable<String> delFlags = getSelectedPatientNo();

            this.btnDelete.Enabled = (delFlags != null && delFlags.Count() > 0) ? true : false;
        }

        private void datGridList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 0)
            {
                return;
            }
            this.btnSerach.Focus();
        }

        private IEnumerable<String> getSelectedPatientNo()
        {
            IEnumerable<DataGridViewRow> enumerableList = datGridList.Rows.Cast<DataGridViewRow>();
            if (enumerableList == null || enumerableList.Count() == 0)
            {
                return null;
            }
            var delPatientNos = from rowItem in enumerableList
                           where (Convert.ToInt32(rowItem.Cells[0].Value) == 1)
                           select "'" + rowItem.Cells[ConstInfo.COL_NUMBER].Value.ToString() + "'";
            return delPatientNos;
        }
    }
}
